//
//  GoodsDetailViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/7/30.
//  Copyright © 2018年 四川中农. All rights reserved.
//

enum GoodsDetailType:Int {
    case none
    case spare  // 立省   捆绑销售类型
    case discount  // 折扣商品
}

import UIKit
import HandyJSON

class GoodsDetailViewController: BaseViewController {
    
    @IBOutlet weak var navHeight: NSLayoutConstraint!
    @IBOutlet weak var navBgView: UIView!
    var header:GoodsDetailHeader!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var backButton: UIButton!
    @IBOutlet weak var rightButton: UIButton!
    @IBOutlet weak var collectButton: UIButton!
    
    var type:GoodsDetailType = .none
    
    var goodsID = 0
    
    var goodsModel:GoodsDetailModel!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        self.tableView.backgroundColor = UIColor.backgroundColor
        
        initHeader()
        
        if #available(iOS 11, *) {
            self.tableView.contentInsetAdjustmentBehavior = .never
        }else{
            self.automaticallyAdjustsScrollViewInsets = false
        }
        self.navigationController?.setNavigationBarHidden(true, animated: true)
        if Utils.isIphoneX() {
            self.navHeight.constant = 88
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(needLogin), name: NSNotification.Name(rawValue: "addCart"), object: nil)
        self.getGoodsDetail()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "addCartNeedLogin"), object: nil)
    }
    
    // MARK:视频播放
    @objc func playVideoMethod(){
        let url = self.goodsModel.goods?.video
        let ctrl = VideoPlayerViewController()
        ctrl.url = url!
        ctrl.name = (self.goodsModel.goods?.name)!
        self.present(ctrl, animated: false, completion: nil)
    }
    
    // MARK:获取商品详情
    func getGoodsDetail(){
        PKhud.show()
        HttpRequest.requestData(.post, URLString: Api.goodsDetail.rawValue, parameters: ["id":self.goodsID  ]) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                if let model = JSONDeserializer<GoodsDetailModel>.deserializeFrom(dict: result["data"] as? postParameters) {
                    self.goodsModel = model
                    self.header.updateSubViews(model: model ,type: self.type)
                    self.collectButton.isSelected = model.goods!.isCollection == 1 ? true : false
                    if model.goods?.isCollection == 1 {
                        self.collectButton.isSelected = true
                    }
                    self.tableView.reloadData()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
      super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func initHeader(){
        self.header = GoodsDetailHeader.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 0))
        self.header.playerClosure = { [weak self] in
            self?.playVideoMethod()
        }
        
        self.tableView.tableHeaderView = self.header
    }
    
    
    // MARK: 返回按钮
    @IBAction func backButtonClick(_ sender: UIButton) {
        self.backBarButtonMethon()
    }
    
    
    // MARK: 右边按钮事件
    @IBAction func rightButtonClick(_ sender: UIButton) {
        
    }
    
    // MARK:跳转购物车
    @IBAction func goShopCart(_ sender: UIButton) {
        guard Utils.isLogined() else {
            PKhud.showText(text: "请先登录~")
            Utils.goLoginCtrol(ctrl: self, isHidenBottomBar: false)
            return
        }
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "ShoppingCartViewController") as! ShoppingCartViewController
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
    // MARK:收藏
    @IBAction func collectClick(_ sender: UIButton) {
        
        guard Utils.isLogined() else {
            PKhud.showText(text: "请先登录~")
            Utils.goLoginCtrol(ctrl: self, isHidenBottomBar: false)
            return
        }
        
        HttpRequest.requestData(.post, URLString: Api.userCollectionAdd.rawValue, parameters: ["goodsId":self.goodsModel.goods?.id as Any,"bigTypeId":self.goodsModel.goods?.bigTypeId as Any]) { (result) in
            if result["msg"] as! String == "success"{
                sender.isSelected = !sender.isSelected
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    // MARK:添加购物车
    @IBAction func addMethod(_ sender: UIButton) {
        guard Utils.isLogined() else {
            PKhud.showText(text: "请先登录~")
            Utils.goLoginCtrol(ctrl: self, isHidenBottomBar: false)
            return
        }
        
        Utils.insertCart(goodsId: self.goodsModel.goods!.id) { (value) in
            if value.0 {
                PKhud.showText(text: "添加成功~")
            }else{
                PKhud.showText(text: value.1)
            }
        }
    }
    
    
}

extension GoodsDetailViewController:UITableViewDelegate,UITableViewDataSource{
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if self.type == .spare {
            if self.goodsModel != nil {
                if self.goodsModel.relevant?.count == 0 {
                    return 4
                }else{
                    return 5
                }
            }else{
                return 0
            }
        }else{
            if self.goodsModel != nil {
                if self.goodsModel.relevant?.count == 0 {
                    return 3
                }else{
                    return 4
                }
            }else{
                return 0
            }
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if self.type == .spare {
            if section == 2 {
                return (self.goodsModel.details?.count)!
            }else{
                return self.goodsModel == nil ? 0 : 1
            }
        }else {
            if section == 1{
                return self.goodsModel == nil ? 0 : (self.goodsModel.details?.count)!
            }
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if self.type == .spare {
            switch indexPath.section {
            case 0:
                let cell = tableView.dequeueReusableCell(withIdentifier: "ActivityExplainTableViewCell") as! ActivityExplainTableViewCell
                cell.descLabel.text = self.goodsModel.goods?.activityDesc
                return cell
            case 1:
                let cell = tableView.dequeueReusableCell(withIdentifier: "ParameterTableViewCell") as! ParameterTableViewCell
                cell.reloadWith(model: self.goodsModel.goods!)
                return cell
            case 2:
                let cell = tableView.dequeueReusableCell(withIdentifier: "GoodsImageTableViewCell") as! GoodsImageTableViewCell
                cell.imageV.my_setImage(url: self.goodsModel.details![indexPath.row], placeholder: Api.placeHolder.rawValue)
                return cell
            case 3:
                let cell =  tableView.dequeueReusableCell(withIdentifier: "GoodsServiceTableViewCell") as! GoodsServiceTableViewCell
                cell.reload(withModel: self.goodsModel.goods!)
                return cell
            case 4:
                let cell = tableView.dequeueReusableCell(withIdentifier: "RecommendationTableViewCell") as! RecommendationTableViewCell
                cell.dataArray = self.goodsModel.relevant!
                cell.backSeleItemID = { [weak self] (id) in
                    let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "GoodsDetailViewController") as! GoodsDetailViewController
                    ctrl.goodsID = id
                    self?.navigationController?.pushViewController(ctrl, animated: true)
                }
                
                return cell
            default:
                return UITableViewCell()
            }
        }else{
            switch indexPath.section + 1 {
            case 1:
                let cell = tableView.dequeueReusableCell(withIdentifier: "ParameterTableViewCell") as! ParameterTableViewCell
                cell.reloadWith(model: self.goodsModel.goods!)
                return cell
            case 2:
                let cell = tableView.dequeueReusableCell(withIdentifier: "GoodsImageTableViewCell") as! GoodsImageTableViewCell
                cell.imageV.my_setImage(url: self.goodsModel.details![indexPath.row], placeholder: Api.placeHolder.rawValue)
                return cell
            case 3:
                let cell =  tableView.dequeueReusableCell(withIdentifier: "GoodsServiceTableViewCell") as! GoodsServiceTableViewCell
                cell.reload(withModel: self.goodsModel.goods!)
                return cell
            case 4:
                let cell = tableView.dequeueReusableCell(withIdentifier: "RecommendationTableViewCell") as! RecommendationTableViewCell
                cell.dataArray = self.goodsModel.relevant!
                cell.backSeleItemID = { [weak self] (id) in
                    let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "GoodsDetailViewController") as! GoodsDetailViewController
                    ctrl.goodsID = id
                    self?.navigationController?.pushViewController(ctrl, animated: true)
                }
                return cell
            default:
                return UITableViewCell()
            }
        }
    }
    
    @objc func needLogin(){
        Utils.goLoginCtrol(ctrl: self, isHidenBottomBar: false)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if self.type == .spare {
            switch indexPath.section {
            case 0,2:
                self.tableView.estimatedRowHeight = 150
                self.tableView.rowHeight = UITableViewAutomaticDimension
                return self.tableView.rowHeight
            case 1:
                return 207
            case 3:
                return 250
            case 4:
                return 227
            default:
                return 0
            }
        }else{
            switch indexPath.section + 1 {
            case 1:
                return 207
            case 2:
                self.tableView.estimatedRowHeight = 150
                self.tableView.rowHeight = UITableViewAutomaticDimension
                return self.tableView.rowHeight
            case 3:
                return 250
            case 4:
                return 227
            default:
                return 0
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section == 0 ? 10 : 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offsetY = scrollView.contentOffset.y
        self.navBgView.alpha = offsetY / 200
        if offsetY > 200 {
            self.backButton.setImage(UIImage.init(named: "icon_return"), for: .normal)
            self.rightButton.setImage(UIImage.init(named: "spxq_icon_more2"), for: .normal)
        }else{
            self.backButton.setImage(UIImage.init(named: "spxq_icon_fanhui"), for: .normal)
            self.rightButton.setImage(UIImage.init(named: "spxq_icon_more"), for: .normal)
        }
    }
}




















